add_type = "none"
// window.pywebview.api.is_ok()
const Page = {
    "index":[document.getElementById("index_page"),document.getElementById("index_b")],
    "main":[document.getElementById("main_page"),document.getElementById("main_b")],
    "setting":[document.getElementById("set_page"),null],
    "char":[document.getElementById("char_page"),document.getElementById("char_b")],
    "video_wpp_edit":[document.getElementById("vid_wpp_edit_page"),null],
    "zj":[document.getElementById("zj_page"),document.getElementById("zj_b")],
}
const old_css = Page["main"].style
function mdui_log(msg){
    mdui.snackbar({
        message: msg,
        position: 'left-bottom',
    });
}
is_load_set = false
let changing = false
async function change_card(id){
    if(changing==true)return
    changing = true
    Page[id][0].className=id+"_page out_pos_a out_op_a"
    await change_card_step_2(id)
    // setTimeout(() => {
    //     change_card_step_2(id)
    // }, 500);
}
async function change_card_step_2(id){
    for(const p in Page){
        this_p = Page[p]
        this_p[0].style.display="none"
        if(this_p[1]==null){
            continue
        }
        this_p[1].style=old_css
    }
    try{Page[id][1].style.backgroundColor="rgb(255,255,255)"}catch{}
    if(id=="main"){
        await load_wpp_show()
    }
    if(id=="char"){
        await load_charRES_local()
        await pack_char_state()
    }
    if(id=="setting" && is_load_set==false){
        // load_setting()
        is_load_set=true
    }
    if(id!="video_wpp_edit"){
        await stop_wpp_editer()
    }
    Page[id][0].className=id+"_page in_pos_a in_op_a"
    if(id=="index"){
        Page[id][0].style.display="block"
        await updateServiceStatus()
    }else{
        Page[id][0].style.display="flex"
    }
    changing = false
}
function start_run_main(){
    // change_card("main")
}
setTimeout(start_run_main,1000)
async function add_HtmlProject(){
    try{
        vid_path = document.getElementById("dir_path_input").value
        paper_name=document.getElementById("dir_name_input").value
        artist_name=document.getElementById("dir_art_input").value
        document.getElementById("full_back").style.display="flex"
        result=await window.pywebview.api.add_Only_html_wp(vid_path,paper_name,artist_name,"index.html","banner.jpg")
        if(result["success"]!=true){
            document.getElementById("full_back").style.display="none"
            mdui_log(result["msg"])
            return
        }
        await window.pywebview.api.wwp_register(result["wpp_id"],"html","banner.jpg",paper_name,artist_name)
        document.getElementById("full_back").style.display="none"
        mdui_log(result["msg"])
        load_wpp_show()
    }catch(e){
        mdui_log('内部错误：'+e)
    }
}
async function add_project(){
    try{
        vid_path = document.getElementById("path_input").value
        paper_name=document.getElementById("name_input").value
        artist_name=document.getElementById("art_input").value
        vid_fz = document.getElementById("vid_fz").checked
        vid_sound = document.getElementById("vid_sound").checked
        document.getElementById("full_back").style.display="flex"
        result=await window.pywebview.api.add_Only_vid_wp(vid_path,paper_name,artist_name,vid_fz,vid_sound)
        if(result["success"]!=true){
            document.getElementById("full_back").style.display="none"
            mdui_log(result["msg"])
            return
        }
        await window.pywebview.api.wwp_register(result["wpp_id"],"video","img.jpg",paper_name,artist_name)
        document.getElementById("full_back").style.display="none"
        mdui_log(result["msg"])
        load_wpp_show()
    }catch(e){
        mdui_log('内部错误：'+e)
    }
}
async function choice_dir(){
    try{
        path = await window.pywebview.api.choise_dir()
        if(path["success"]==true){
            document.getElementById("dir_path_input").value = path["data"]
        }else{
            mdui_log(data["msg"])
        }
    }catch(e){
        mdui_log("未知错误:"+e)
    }
}
async function create(c_type){
    try{
        add_type = c_type
        path = await window.pywebview.api.choise_file()
        if(path["success"]==true){
            document.getElementById("path_input").value = path["data"]
        }else{
            mdui_log(data["msg"])
        }
    }catch(e){
        mdui_log("未知错误:"+e)
    }
}
async function show_inf(wpp_id){
    try{
        try{document.getElementById("state_content").remove()}catch{}
        try{document.getElementById("no_infShow").remove()}catch{}
        data=await window.pywebview.api.get_wpp_list()
        if(data["success"]==true){
            wpp = data["data"][wpp_id]
            action_btn = `
                <button class='inf_bottom_b blue_btn' onclick="edit_wpp('${wpp["id"]}')"><a href="javascript:void(0);">编辑壁纸</a></button>
                <button class='inf_bottom_b red_btn' onclick="remove_wpp('${wpp["id"]}')"><a href="javascript:void(0);">删除壁纸</a></button>`
            new_inf_bar=document.createElement("div")
            new_inf_bar.className="state_content_bar"
            new_inf_bar.id="state_content"
            new_inf_bar.innerHTML=`
            <p>名称：${wpp["name"]}</p>
            <p>制作者：${wpp["editor"]}</p>
            <p>艺术家：${wpp["artist"]}</p>
            <p>大小：${wpp["size"]}</p>
            <button class='inf_bottom_b green_btn' onclick="start_wpp('${wpp["id"]}')"><a href="javascript:void(0);">启用壁纸</a></button>
            <div class="wpp_file_deal_btn">
                ${action_btn}
            </div>
            `
            document.getElementById("inf_bar_html").appendChild(new_inf_bar)
        }else{
            mdui_log("壁纸信息拉取失败:"+data["msg"])
        }
    }catch(e){
        show_inf(wpp_id)
    }
}
async function stop_wpp(){
    window.pywebview.api.stop_wpp()
    set_no()
}
async function set_no(){
    try{document.getElementById("wp_inf_bar").remove()}catch{}
    a=document.getElementById("now_wp_bar")
    b=document.createElement("h1")
    b.className = "no_wpp_content"
    b.id="wp_inf_bar"
    b.innerText=`当前无壁纸放映`
    a.appendChild(b)
}
async function is_run(){
    try{
        r = await window.pywebview.api.is_wpp_run()
        check_and_pack_wppService()
        if(r["success"]==true){
            if(r["result"]==true){
                if(r["full"]["open"]==false){
                    set_no()
                    return
                }
                try{document.getElementById("wp_inf_bar").remove()}catch{}
                a=document.getElementById("now_wp_bar")
                b=document.createElement("div")
                b.className = "now_wppBox"
                b.id="wp_inf_bar"
                b.innerHTML=`
                    <h3>壁纸id: ${r["wppId"]}</h3>
                    <p id="wpp_state">正在运行</p>
                    <button class="stop_wpp_button"><a href="javascript:void(0)" onclick="stop_wpp()">停止壁纸运行服务</a></button>
                `
                a.appendChild(b)
                return
            }
        }
        set_no()
    }catch(e){
        mdui_log(e)
        // is_run()
    }
}
// setTimeout(is_run,500)
async function start_wpp(wpp_id){
    // await window.pywebview.api.stop_wpp()
    try{
        try{document.getElementById("wp_inf_bar").remove()}catch{}
        a=document.getElementById("now_wp_bar")
        b=document.createElement("div")
        b.className = "now_wppBox"
        b.id="wp_inf_bar"
        b.innerHTML=`
            <h3>壁纸id: ${wpp_id}</h3>
            <p id="wpp_state">正在启动中....</p>
            <button class="stop_wpp_button"><a href="javascript:void(0)" onclick="stop_wpp()">停止壁纸运行服务</a></button>
            <div class="mdui-progress" id="wpp_state_pro" style="padding-top:10px">
                <div class="mdui-progress-indeterminate"></div>
            </div>
        `
        a.appendChild(b)
        await window.pywebview.api.start_wpp(wpp_id)
        try{document.getElementById("wpp_state_pro").remove()}catch{}
        try{document.getElementById("wpp_state").innerText="正在运行"}catch{}

    }catch(e){
        mdui_log(e)
    }
}
async function remove_wpp(wid){
    await window.pywebview.api.remove_wpp(wid)
    load_wpp_show()
    try{document.getElementById("state_content").remove()}catch{}
    try{document.getElementById("no_infShow").remove()}catch{}
    new_inf_e = document.createElement("div")
    new_inf_e.className="no_infShow_out"
    new_inf_e.id="no_infShow"
    new_inf_e.innerHTML=`
    <div class="no_infShow">
        <div>
            <img src="./resources/no_data.png">
        </div>
        <h2>没有信息</h2>
    </div>`
    document.getElementById("inf_bar_html").appendChild(new_inf_e)
}
async function load_wpp_show(){
    document.getElementById("777").remove()
    new_project_card = document.createElement("div")
    // <div class="project_card" id="777"></div>
    new_project_card.className="project_card"
    new_project_card.id="777"
    document.getElementById("select_wpp_bar").appendChild(new_project_card)
    // data = {"success":true,"data":{'7g6RL1S9se': {'id': '7g6RL1S9se', 'name': '崩坏星穹铁道', 'img': 'img.jpg', 'editor': 'miHoYo', 'artist': '未知', 'describe': '暂无简介', 'size': 'unkonw'}}}
    data=await window.pywebview.api.get_wpp_list()
    if(data["success"]==true){
        var count = 0
        for(wwp in data["data"]){
            count+=1
            wwp=data["data"][wwp]
            console.log(wwp)
            new_e=document.createElement("div")
            new_e.className="new_pCard"
            if(wwp["type"]!='video'){
                new_e.innerHTML=`
                <a href="javascript:void(0);" onclick="show_inf('${wwp["id"]}')">
                    <div class="pBorder">
                        <div class="img_card" style="background-image: url('wallpaper/${wwp["id"]}/${wwp["img"]}')"></div>
                        <div class="inf_card">
                            <h4>${wwp["name"]}</h4>
                            <p>创作者：${wwp["artist"]}</p>
                        </div>
                    </div>
                </a>
                `
            }else{
                new_e.innerHTML=`
                <a href="javascript:void(0);" onclick="show_inf('${wwp["id"]}')">
                    <div class="pBorder">
                        <div class="wpp_vidBanner_card">
                            <video id="vid_banner_${wwp["id"]}" src="wallpaper/${wwp["id"]}/video.mp4" muted loop></video>
                        </div>
                        <div class="inf_card">
                            <h4>${wwp["name"]}</h4>
                            <p>创作者：${wwp["artist"]}</p>
                        </div>
                    </div>
                </a>
                `
            }
            // new_e.setAttribute("onclick",`show_inf('${wwp["id"]}')`)
            // new_e.innerHTML=`
            // <div class="name_card">
            //     <p class="wwp_title">${wwp["name"]}</p>
            // </div>
            // `
            // new_e.style.backgroundImage=`url('wallpaper/${wwp["id"]}/${wwp["img"]}')`
            // new_e.style.backgroundSize="cover"
            // new_e.style.backgroundRepeat="no-repeat"
            // new_e.style.backgroundPosition="center"
            new_project_card.appendChild(new_e)
        }
        setTimeout(async function(){
            for(wwp in data["data"]){
                var vid_banner = document.getElementById("vid_banner_"+wwp)
                vid_banner.style.width="200px"
                console.log(wwp+" "+vid_banner.clientHeight)
                if(vid_banner.clientHeight >90){
                    var offset = (vid_banner.clientHeight-90)/2
                    vid_banner.style.marginTop=-offset+"px"
                }else if(vid_banner.clientHeight<90){
                    vid_banner.style.width="unset"
                    vid_banner.style.height="90px"
                    var offset = (vid_banner.clientWidth-200)/2
                    vid_banner.style.marginLeft=-offset+"px"
                }else{
                    vid_banner.style.width="200px"
                }
                vid_banner.addEventListener('mouseover', function() {
                    this.play();
                });
                vid_banner.addEventListener('mouseout', function() {
                    this.pause();
                });
            }
        },500)
        if(count<=0){
            new_e = document.createElement("div")
            new_e.className="no_wppShow mrq"
            new_e.innerHTML=`
                <img src="./resources/img/mrq_3.png">
                <h3>欢迎使用梦幻空间!!</h3>
                <h3>快来添加壁纸吧~</h3>`
            new_project_card.appendChild(new_e)
        }
        fit_winSize()
    }else{
        mdui_log("壁纸信息拉取失败:"+data["msg"])
    }
}
async function fit_winSize(){
    bar_list = [document.getElementById("777"),document.getElementById("cil_bar")]
    e_width = [200,320]
    b_range = 0
    for(box of bar_list){
        var n = Math.floor(box.clientWidth / e_width[b_range])
        // console.log("容器长度"+box.clientWidth+"计算得出每行n="+n)
        if(box.children.length >= n){
            var margin = ((box.clientWidth-(n*e_width[b_range]))/n)/2.2
            // console.log(box.clientWidth-(n*e_width[b_range]))
            // console.log("剩余空间"+box.clientWidth-(n*e_width[b_range])+"除n+1得到"+(box.clientWidth-(n*e_width[b_range]))/(n+1))
            var set_range = 0
            for(wpp_e of box.children){
                if(set_range==0 || set_range%n == 0){
                    wpp_e.style.marginLeft=margin+"px"
                }
                wpp_e.style.marginRight=margin+"px"
                wpp_e.style.marginTop="10px"
            }
        }else{
            for(wpp_e of box.children){
                if(wpp_e.className!="no_wppShow mrq")wpp_e.style.margin = "5px"
            }
        }
        b_range += 1
        // console.log("____________")
    }
}
window.addEventListener('resize',async function() {
    await fit_winSize()
});
function load_ui(){
    document.getElementById("select_wpp_bar").style.height=window.innerHeight*0.83+"px"
    try{
        document.getElementById("777").style.height=window.innerHeight*0.6+"px"
    }catch{}
}
load_ui()
setInterval(load_ui,1000)

let uploading = false
async function load_charRES_web(){
    document.getElementById("char_web_iframe").src="/res_store_char.html"
    pack_charRES({},"waiting")
    // document.getElementById("char_web_iframe").style.display = "block" 
    // document.getElementById("cil_bar").style.display = "none"
    // pack_charRES({},"waiting")
    document.getElementById("char_local").style.color="rgb(200,200,200)"
    document.getElementById("char_web").style.color="rgb(0, 255, 213)"
    // try{
    //     var charRES = await window.pywebview.api.get_charRES_web()
    // }catch{
    //     mdui_log("网络错误，无法获取信息")
    // }
    // pack_charRES(charRES,"web")
}
async function load_charRES_local(){
    document.getElementById("char_web_iframe").style.display = "none" 
    document.getElementById("cil_bar").style.display = "block"
    document.getElementById("char_web").style.color="rgb(200,200,200)"
    document.getElementById("char_local").style.color="rgb(0, 230, 190)"
    var charRES = await window.pywebview.api.get_charRES_local()
    pack_charRES(charRES,"local")
}
async function had_dl(net_id){
    var charRES = await window.pywebview.api.get_charRES_local()
    for(c of charRES["data"]){
        if(c["net_id"]==net_id){
            return true
        }
    }
    return false
}
async function pack_charRES(wppRES,type){
    try{document.getElementById("cil_bar").remove()}catch{}
    cil_bar = document.createElement("div")
    cil_bar.className="charInf_list_bar"
    cil_bar.id = "cil_bar"
    var have_data = false
    try{
        wppRES["len"]
        if(wppRES["len"]==0){
            have_data = false
        }else{
            have_data = true
        }
    }catch{
        have_data = false
    }
    if(type=="waiting"){
        nodata_div = document.createElement("div")
        nodata_div.style="width:100%"
        nodata_div.innerHTML=`<div style="width:100%">
        <img class="rotating-element" style="display:flex;width:100px;height:100px;margin: auto;" src="./resources/loading_gIco.png">
        <h3 style="color: #00d1ad;text-align: center;">加载中...</h3>
        </div>`
        cil_bar.appendChild(nodata_div)
    }
    else if (have_data==false){
        nodata_div = document.createElement("div")
        nodata_div.style="width:100%"
        nodata_div.innerHTML=`<div style="width:100%">
        <img style="display:flex;width:100px;height:100px;margin: auto;" src="./resources/no_data.png">
        <h3 style="color: rgb(200,200,200);text-align: center;">这里居然什么也没有诶</h3>
        </div>`
        cil_bar.appendChild(nodata_div)
    }else{
        for(obj of wppRES["data"]){
            btn=""
            if(type=="web"){
                obj["banner"]="https://media-api.code-vicent.top/get/small_"+obj["banner"]
                if(await had_dl(obj["net_id"])==true){
                    btn_html=`
                    <a href="javascript:void(0);">
                        <div class="dl_btn unactive_dlBtn">
                            <p>已下载</p>
                        </div>
                    </a>
                    `
                }else{
                    btn_html=`
                    <a href="javascript:void(0);" onclick="download_char('${obj["net_id"]}',this)">
                        <div class="dl_btn active_dlBtn">
                            <p>下载</p>
                        </div>
                    </a>
                    `
                }
            }else{
                obj["banner"]="char/"+obj["key_name"]+"/"+obj["banner"]
                if(obj["create_local"]==false){
                    edit_btn = ""
                }else{
                    edit_btn=`
                    <a onclick="window.pywebview.api.start_charEdit('${obj["key_name"]}')" class="action_button" style="width: 70px;" href="javascript:void(0);">
                        <div style="margin-left:0px;">
                            <img src="./resources/edit.png">
                            <p>编辑</p>
                        </div>
                    </a>
                    `
                }
                var run_data = await window.pywebview.api.is_char_run()
                if(run_data["result"]==true && run_data["charId"]==obj["key_name"]){
                    start_btn=`
                    <div class="action_button" style="display:flex;margin-left:5px;margin-right: 0px;">
                        <img style="width:20px;height:20px;margin-top:auto;margin-bottom:auto;" src="./resources/running.png">
                        <p style="margin-top:auto;margin-bottom:auto;color:#00d1ad;">运行中</p>
                    </div>
                    `
                }else{
                    start_btn=`
                    <a onclick="use_char('${obj["key_name"]}',this)" class="action_button" style="width:70px;" href="javascript:void(0);">
                        <div style="margin-left:0px;margin-right: 0px;">
                            <img src="./resources/start_ico.png">
                            <p>启用</p>
                        </div>
                    </a>
                    `
                }
                btn_html = `
                <div class="char_actionBox">
                    ${start_btn}
                    ${edit_btn}
                    <a onclick="del_char('${obj["key_name"]}')" class="action_button" href="javascript:void(0);">
                        <div style="margin-left:0px;">
                            <img src="./resources/icon-delete.png">
                        </div>
                    </a>
                </div>
                `
            }
            new_char = document.createElement("div")
            new_char.className = "charInf_bar"
            new_char.innerHTML=`
            <div class="inside_bar">
                <div class="charImg_box"><img src="${obj["banner"]}"></div>
                <div class="char_inf_bar">
                    <h2>${obj["name"]}</h2>
                    <div class="introduct_box">
                        <p>${obj["introduce"]}</p>
                    </div>
                    ${btn_html}
                </div>
            </div>
            `
            // new_char.innerHTML=`
            // <div class="inside_bar">
            //     <img class="list_image" src="${obj["banner"]}">
            //     <h3 style="padding-left:20px;">${obj["name"]}</h3>
            //     <div class="char_btn_bar">
            //         ${btn}
            //     </div>
            // </div>`
            cil_bar.appendChild(new_char)
        }
    }
    document.getElementById("clb").appendChild(cil_bar)
    fit_winSize()
}
let downloading = false
async function download_char(char_id,e){
    if(downloading==true)return
    downloading = true
    downloadingDialog.open()
    closeWorkDetail()
    var r = await window.pywebview.api.download_char(char_id)
    document.getElementById("loading_mask").style.display="none"
    downloadingDialog.close()
    downloading = false
    if(r["success"]==true){
        mdui_log("下载成功！")
        e.children[0].className = "dl_btn unactive_dlBtn"
        e.children[0].children[0].innerText = "已下载"
    }else{
        mdui_log("下载失败，"+r["msg"])
    }
}
async function del_char(key){
    mdui.dialog({
        title: '删除角色',
        content: '你确定要删除角色'+key+"吗？",
        buttons: [
            {
            text: '取消'
            },
            {
            text: '确认',
                onClick: async function(inst){
                    await window.pywebview.api.del_char(key)
                    mdui_log("删除成功")
                    load_charRES_local()
                }
            }
        ]
    });
}
async function use_char(char,e){
    e.children[0].children[0].src="./resources/loading_gIco.png"
    e.children[0].children[0].className="rotating-element"
    await window.pywebview.api.start_char(char)
    await load_charRES_local()
    await pack_char_state()
}
async function pack_char_state(){
    state_data = await window.pywebview.api.is_char_run()
    chars_data = await window.pywebview.api.get_charRES_local_original()
    if(state_data["result"]==true){
        document.getElementById("running_charName").innerText=chars_data["data"][state_data["charId"]]["name"]
        document.getElementById("running_charImg").src= "char/"+state_data["charId"]+"/"+chars_data["data"][state_data["charId"]]["banner"]
        document.getElementById("stop_char_btn").style.display="block"
    }else{
        document.getElementById("running_charName").innerText="未启用"
        document.getElementById("running_charImg").src="./resources/no_data.png"
        document.getElementById("stop_char_btn").style.display="none"
    }
}
const name_editInput_e = document.getElementById("wpp_name_input")
const editer_editInput_e = document.getElementById("wpp_editer_input")
const fx_editInput_e = document.getElementById("edit_jx")
const sound_editInput_e = document.getElementById("edit_sound")
const size_editInput_e = document.getElementById("size_input")
const offset_editInput_e = document.getElementById("offset_input")
const char_linkInput_e = document.getElementById("char_select")
let now_edit_type = ""
let set_vid_state_progress = null
async function load_vid_edit(wppId){
    var data = await window.pywebview.api.get_wppPackData(wppId)
    now_edit_type = data["inf"]["type"]
    if(data["inf"]["type"]!="video"){
        document.getElementById("vid_view").style.display="none"
        document.getElementById("vid_view_iframe").style.display="block"
        document.getElementById("vid_view_iframe").src = "wallpaper/"+wppId+"/index.html"
    }else{
        document.getElementById("vid_view").style.display="block"
        document.getElementById("vid_view_iframe").style.display="none"
        document.getElementById("vid_view").src = data["pack"]["vid"]
        update_wpp_state()
        set_vid_state()
    }
    name_editInput_e.value = data["inf"]["name"]
    editer_editInput_e.value = data["inf"]["editor"]
    if(data["inf"]["type"]=="video"){
        fx_editInput_e.checked = data["pack"]["is_jx"]
        sound_editInput_e.checked = data["pack"]["sound"]
        size_editInput_e.value = data["pack"]["size"]
        offset_editInput_e.value = data["pack"]["offset"]
        update_wpp_state([data["pack"]["size"],data["pack"]["offset"]])
    }
    var n_list = ["vid_wpp_edit_jx","vid_wpp_edit_sy","vid_wpp_edit_pack","vid_wpp_edit_pack_text"]
    if(data["inf"]["type"]!="video"){
        var vis = "hidden"
    }else{
        var vis = ""
    }
    for(e_n of n_list){
        document.getElementById(e_n).style.visibility=vis
    }
    document.getElementById("edit_show_wppid").innerText=wppId
    char_select_html = '<option value="unuse">不使用</option>'
    char_data=await window.pywebview.api.get_charRES_local_original()
    for(n in char_data["data"]){
        char_select_html+=` <option value="${char_data["data"][n]["key_name"]}">${char_data["data"][n]["name"]}</option>`
    }
    document.getElementById("char_select").innerHTML=char_select_html
    char_linkInput_e.value=data["inf"]["char_link"]
    if(data["inf"]["type"]=="video"){
        set_vid_state_progress = setInterval(set_vid_state,500)
    }
}
async function edit_wpp(wppId){
    await load_vid_edit(wppId)
    change_card("video_wpp_edit")
}
function update_wpp_state(data=[]){
    console.log(data)
    if(data.length!=0){
        document.getElementById("vid_view").style.width=data[0]+"%"
        document.getElementById("vid_view").style.marginLeft=-data[1]+"px"
    }
    if(fx_editInput_e.checked == true){
        document.getElementById("vid_view").className = "video_jx"
    }else{
        document.getElementById("vid_view").className = ""
    }
    if(sound_editInput_e.checked == false){
        document.getElementById("vid_view").muted = true;
    }else{
        document.getElementById("vid_view").muted = false;
    }
}
async function set_vid_state(){
    var size_value=Number(size_editInput_e.value)
    var offset_value=Number(offset_editInput_e.value)
    if(document.getElementById("edit_center").checked==true){
        var offset_v = (document.getElementById("vid_view").offsetWidth - document.getElementById("vid_view_bar").offsetWidth)/2
        offset_editInput_e.value=offset_v
        update_wpp_state([size_value,offset_v])
    }
    size_editInput_e.onchange=function(){
        var size_value=Number(size_editInput_e.value)
        if(size_value<100){
            size_value=100
            size_editInput_e.value=100
        }else if(size_value>500){
            size_value = 500
            size_editInput_e.value=500
        }
        update_wpp_state([size_value,offset_value])
    }
    offset_editInput_e.onchange=function(){
        var offset_value=Number(offset_editInput_e.value)
        if(offset_value<0){
            offset_value = 0
            offset_editInput_e.value=0
        }
        update_wpp_state([size_value,offset_value])
    }
    fx_editInput_e.onchange=function(){
        update_wpp_state()
    }
    sound_editInput_e.onchange=function(){
        update_wpp_state()
    }
}
async function stop_wpp_editer(){
    document.getElementById("vid_view").src = ""
    document.getElementById("vid_view_iframe").src = ""
    clearInterval(set_vid_state_progress)
}
async function save_wppEdit(){
    await window.pywebview.api.update_wppPack(
        document.getElementById("edit_show_wppid").innerText,
        name_editInput_e.value,
        editer_editInput_e.value,
        fx_editInput_e.checked,
        sound_editInput_e.checked,
        size_editInput_e.value,
        offset_editInput_e.value,
        char_linkInput_e.value,
        now_edit_type
    )
    mdui_log("保存成功")
}
async function stop_char(){
    await window.pywebview.api.stop_char()
    await load_charRES_local()
    await pack_char_state()
}

const every_day_openInput = document.getElementById("everyday_openInput")
const every_day_pathShow = document.getElementById("every_day_path")
async function pack_ed(){
    ed_data = await window.pywebview.api.get_ed_state()
    if(ed_data["data"]["on"]=="on"){
        every_day_openInput.checked=true
    }else{
        every_day_openInput.checked=false
    }
    every_day_pathShow.innerText=ed_data["path"]
}
every_day_openInput.onchange = function(){
    window.pywebview.api.set_everyDay_state(every_day_openInput.checked)
}
async function change_everyday_path(){
    path = await window.pywebview.api.choise_file()
    if(path["success"]==true){
        console.log("edPath")
        path=path["data"][0]
        every_day_pathShow.innerText=path
        window.pywebview.api.set_everyDay_path(path)
    }
}
async function load_edit_vid(){
    var data = await window.pywebview.api.get_screen()
    var bl = 1
    if(data["w"]>data["h"]){
        while(true){
            if(330>(data["w"]*bl)){
                break
            }else{
                bl-=0.01
            }
        }
    }else{
        while(true){
            if(185>(data["h"]*bl)){
                break
            }else{
                bl-=0.01
            }
        }
    }
    document.getElementById("vid_view_bar").style.width=(data["w"]*bl)+"px"
    document.getElementById("vid_view_bar").style.height=(data["h"]*bl)+"px"
    window.pywebview.api.report_bl(bl)
    console.log(bl)
}
async function plug_pack(){
    pb = document.getElementById("plug_pack")
    plug_data = {
        "dsr":{
            "ico":"./resources/date_count_ico.png",
            "name":"倒数日",
            "src":"./plug/date.ui.html"
        }
    }
    for(p in plug_data){
        var this_p = plug_data[p]
        new_p = document.createElement("div")
        new_p.className="zj"
        new_p.innerHTML=`
        <div class="zj_inf_bar">
            <img src="${this_p["ico"]}" width="50px" height="50px">
            <p>${this_p["name"]}</p>
        </div>
        <iframe src="${this_p["src"]}" id="plug_iframe"></iframe>
        `
        pb.appendChild(new_p)
    }
}
function close_update(){
    document.getElementById("update_mask").style.display="none"
}
function go_update(){
    window.pywebview.api.go_link('https://code-vicent.top/url/wpp_update')
    close_update()
}
async function get_loginAccess(){
    access = await window.pywebview.api.get_loginAccess()
    post("cv-api","/account/reg_access/",{"access":access["access"]},async function(data){
        console.log(data)
    })
}
// 等待pywebview加载
service_check_task = null
let downloadingDialog
window.addEventListener('pywebviewready',async function() {
    console.log('pywebview is ready');
    // await load_setting()
    await load_edit_vid()
    await pack_ed()
    await plug_pack()
    await is_run()
    setInterval(updateServiceStatus, 2000);
    initServiceControls();
    document.getElementById("starting").style.display="none"
    change_card("index")
    // service_check_task=setInterval(check_and_pack_wppService,1000)
    v=await window.pywebview.api.get_v()
    document.getElementById("v_show").innerText = "当前版本："+v["v"]

    check_update = await window.pywebview.api.check_update()
    if(check_update["need_update"]==true){
        document.getElementById("v_pack").innerText=`更新: V${check_update["data"]["v"]}`
        document.getElementById("update_txt").innerText=check_update["inf"]
        document.getElementById("update_mask").style.display="flex"
    }
    downloadingDialog = new mdui.Dialog('#downloadingDialog', {
        modal: true,
        closeOnEsc: false,
        closeOnConfirm: false
    });
    get_loginAccess()
    // document.querySelector('.status-card:nth-of-type(1) .switch input').onchange = async function () {
    //     await window.pywebview.api.set_autoStartConfig("wpp",this.checked)
    // };
    // document.querySelector('.status-card:nth-of-type(2) .switch input').onchange = async function () {
    //     await window.pywebview.api.set_autoStartConfig("wpp",this.checked)
    // };
    // document.querySelector('.status-card:nth-of-type(3) .switch input').onchange = async function (){
    //     await window.pywebview.api.set_autoStartConfig("easyDesktop",this.checked)
    // }
})
window.plugAPI={
    readData:async function(pid){
        return await window.pywebview.api.plug_readData(pid)
    },
    dumpData:async function(pid,data){
        return await window.pywebview.api.plug_dumpData(pid,data)
    }
}
async function login_deal(){
    if(document.getElementById("user_name_bar").innerText!="登录"){
        window.pywebview.api.open_person()
    }else{
        open_login()
    }
}
wsp = document.getElementById("wpp_service_p")
wsb = document.getElementById("wpp_service_b")
async function check_and_pack_wppService(){
    var r = await window.pywebview.api.is_wppService_run()
    if(r["result"]==true){
        wsp.innerText="壁纸及组件服务运行中..."
        wsb.style.display="none"
    }else{
        wsp.innerText="壁纸及组件服务未启动"
        wsb.style.display="flex"
    }
}
async function run_service(){
    clearInterval(service_check_task)
    wsb.style.display="none"
    wsp.innerText="正在启动服务..."
    r=await window.pywebview.api.start_service()
    if(r["success"]==false)mdui_log("启动失败")
    check_and_pack_wppService()
    // service_check_task=setInterval(check_and_pack_wppService,1000)
}

// 主页
// 状态更新函数
async function updateServiceStatus() {
        // 获取运行状态和服务配置
        const runState = await window.pywebview.api.check_runState();
        let autoStartConfig = await window.pywebview.api.get_autoStartConfig();
        autoStartConfig = autoStartConfig["data"]
        // 更新动态壁纸服务状态
        if (runState.data.wpp) {
            document.querySelector('.status-card:nth-of-type(1) .status-tag').className = 'status-tag running';
            document.querySelector('.status-card:nth-of-type(1) .status-tag').textContent = '运行中';
            document.querySelector('.status-card:nth-of-type(1) .action-button').className = 'action-button stop-btn';
            document.querySelector('.status-card:nth-of-type(1) .action-button').innerText = "停止"
            document.querySelector('.status-card:nth-of-type(1) .action-button').onclick=null
            document.querySelector('.status-card:nth-of-type(1) .action-button').onclick = async function () {
                await window.pywebview.api.stop_service();
            };
        } else {
            document.querySelector('.status-card:nth-of-type(1) .status-tag').className = 'status-tag stopped';
            document.querySelector('.status-card:nth-of-type(1) .status-tag').textContent = '未运行';
            document.querySelector('.status-card:nth-of-type(1) .action-button').className = 'action-button start-btn';
            document.querySelector('.status-card:nth-of-type(1) .action-button').innerText = "开启"
            document.querySelector('.status-card:nth-of-type(1) .action-button').onclick=null
            document.querySelector('.status-card:nth-of-type(1) .action-button').onclick = async function () {
                await window.pywebview.api.start_service();
            };
        }
        
        // 更新角色互动服务状态
        if (runState.data.char) {
            document.querySelector('.status-card:nth-of-type(2) .status-tag').className = 'status-tag running';
            document.querySelector('.status-card:nth-of-type(2) .status-tag').textContent = '运行中';
            document.querySelector('.status-card:nth-of-type(2) .action-button').className = 'action-button stop-btn';
            document.querySelector('.status-card:nth-of-type(2) .action-button').innerText = "停止"
            document.querySelector('.status-card:nth-of-type(2) .action-button').onclick=null
            document.querySelector('.status-card:nth-of-type(2) .action-button').onclick = async function () {
                await stop_char()
            };
        } else {
            document.querySelector('.status-card:nth-of-type(2) .status-tag').className = 'status-tag stopped';
            document.querySelector('.status-card:nth-of-type(2) .status-tag').textContent = '未运行';
            document.querySelector('.status-card:nth-of-type(2) .action-button').className = 'action-button start-btn';
            document.querySelector('.status-card:nth-of-type(2) .action-button').innerText = "开启"
            document.querySelector('.status-card:nth-of-type(2) .action-button').onclick=null
            document.querySelector('.status-card:nth-of-type(2) .action-button').onclick = async function () {
                await change_card("char")
            };
        }
        
        // 更新简易桌面服务状态
        if (runState.data.easyDesktop) {
            document.querySelector('.status-card:nth-of-type(3) .status-tag').className = 'status-tag running';
            document.querySelector('.status-card:nth-of-type(3) .status-tag').textContent = '运行中';
            document.querySelector('.status-card:nth-of-type(3) .action-button').className = 'action-button stop-btn';
            document.querySelector('.status-card:nth-of-type(3) .action-button').innerText = "停止"
            document.querySelector('.status-card:nth-of-type(3) .action-button').onclick=null
            document.querySelector('.status-card:nth-of-type(3) .action-button').onclick = async function () {
                await window.pywebview.api.stop_ED();
            };
        } else {
            document.querySelector('.status-card:nth-of-type(3) .status-tag').className = 'status-tag stopped';
            document.querySelector('.status-card:nth-of-type(3) .status-tag').textContent = '未运行';
            document.querySelector('.status-card:nth-of-type(3) .action-button').className = 'action-button start-btn';
            document.querySelector('.status-card:nth-of-type(3) .action-button').innerText = "开启"
            document.querySelector('.status-card:nth-of-type(3) .action-button').onclick=null
            document.querySelector('.status-card:nth-of-type(3) .action-button').onclick = async function () {
                await window.pywebview.api.start_ED();
            };
        }
        
        // 更新自启动开关状态
        document.querySelector('.status-card:nth-of-type(1) .switch input').checked = autoStartConfig.wpp;
        document.querySelector('.status-card:nth-of-type(2) .switch input').checked = autoStartConfig.char;
        document.querySelector('.status-card:nth-of-type(3) .switch input').checked = autoStartConfig.easyDesktop;
}

// 初始化事件监听器
function initServiceControls() {
    // 动态壁纸服务控制
    const wppStartBtn = document.querySelector('.status-card:nth-of-type(1) .start-btn');
    const wppStopBtn = document.querySelector('.status-card:nth-of-type(1) .stop-btn');
    
    if (wppStartBtn) {
        wppStartBtn.addEventListener('click', async () => {
            // 这里需要根据实际情况调用启动服务的方法
            // 示例方法，您可能需要修改
            await startWallpaperService();
            await updateServiceStatus();
        });
    }
    
    if (wppStopBtn) {
        wppStopBtn.addEventListener('click', async () => {
            // 这里需要根据实际情况调用停止服务的方法
            // 示例方法，您可能需要修改
            await stopWallpaperService();
            await updateServiceStatus();
        });
    }
    
    // 角色互动服务控制
    const charStartBtn = document.querySelector('.status-card:nth-of-type(2) .start-btn');
    const charStopBtn = document.querySelector('.status-card:nth-of-type(2) .stop-btn');
    
    if (charStartBtn) {
        charStartBtn.addEventListener('click', async () => {
            // 这里需要根据实际情况调用启动服务的方法
            // 示例方法，您可能需要修改
            // await startCharacterService();
            // await updateServiceStatus();
        });
    }
    
    if (charStopBtn) {
        charStopBtn.addEventListener('click', async () => {
            // 这里需要根据实际情况调用停止服务的方法
            // 示例方法，您可能需要修改
            await stopCharacterService();
            await updateServiceStatus();
        });
    }
    
    // 简易桌面服务控制
    const desktopStartBtn = document.querySelector('.status-card:nth-of-type(3) .start-btn');
    const desktopStopBtn = document.querySelector('.status-card:nth-of-type(3) .stop-btn');
    
    if (desktopStartBtn) {
        desktopStartBtn.addEventListener('click', async () => {
            // 这里需要根据实际情况调用启动服务的方法
            // 示例方法，您可能需要修改
            await startEasyDesktopService();
            await updateServiceStatus();
        });
    }
    
    if (desktopStopBtn) {
        desktopStopBtn.addEventListener('click', async () => {
            // 这里需要根据实际情况调用停止服务的方法
            // 示例方法，您可能需要修改
            await stopEasyDesktopService();
            await updateServiceStatus();
        });
    }
    
    // 自启动开关事件监听
    const autoStartSwitches = document.querySelectorAll('.toggle-wrapper .switch input');
    
    if (autoStartSwitches[0]) {
        autoStartSwitches[0].addEventListener('change', async (e) => {
            console.log("自启动开关状态改变")
            await window.pywebview.api.set_autoStartConfig('wpp', e.target.checked);
        });
    }
    
    if (autoStartSwitches[1]) {
        autoStartSwitches[1].addEventListener('change', async (e) => {
            await window.pywebview.api.set_autoStartConfig('char', e.target.checked);
        });
    }
    
    if (autoStartSwitches[2]) {
        autoStartSwitches[2].addEventListener('change', async (e) => {
            await window.pywebview.api.set_autoStartConfig('easyDesktop', e.target.checked);
        });
    }
}

// 以下方法是示例方法，需要根据实际情况进行调整
async function startWallpaperService() {
    r=await window.pywebview.api.start_service()
    if(r["success"]==false)mdui_log("启动失败")
}

async function showWorkDetail(workId) {
    let had_loadCharList = await window.pywebview.api.get_webChar()
    had_loadCharList = had_loadCharList.data
    try {
        // 获取作品详细信息
        const response = await fetch(`http://127.0.0.1:8001/content/get/wpp_char?cid=${workId}`);
        const data = await response.json();
        
        if (data.success) {
            const work = data.data[0];
            if(workId in had_loadCharList){
                if(Number(had_loadCharList[workId])<work.v){
                    action = "更新"
                    class_name = "download_btn"
                    dl_action = `download_char('${workId}')`
                }else{
                    action = "已下载"
                    class_name = "had_download_btn"
                    dl_action = ""
                }
            }else{
                action = "下载作品"
                class_name = "had_download_btn"
                dl_action = `download_char('${workId}')`
            }
            // 创建详细信息内容
            const detailContent = document.getElementById('work_detail_inner');
            detailContent.innerHTML = `
                <div class="work_detail_cover" style="background-image: url('${work.img}');"></div>
                <div class="work_detail_info">
                    <div>
                        <h3>${work.title}</h3>
                        <p>作者：${work.author.name}</p>
                        <p class="rating_text">下载量：${work.view_data.collect}</p>
                        <p class="rating_text">简介：${work.content.introduce}</p>               
                        <button class="${class_name}" onclick="${dl_action}">${action}</button>
                    </div>
                </div>
            `;
            
            // 显示弹窗
            document.getElementById("comment_iframe").src = `http://127.0.0.1:8001/comment?content_id=${workId}`
            document.getElementById('work_detail_modal').style.display = 'flex';
        } else {
            mdui_log('获取作品详情失败: ' + data.msg);
        }
    } catch (error) {
        mdui_log('网络错误: ' + error);
    }
}
function closeWorkDetail() {
    document.getElementById('work_detail_modal').style.display = 'none';
}
